package Audio;

import Network.ClientUDP;
import controleur.AbstractChatControleur;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import javax.sound.sampled.*;
import model.soundSetting;

/**
 * La classe AudioCapture<br>
 * Elle capture le son de l'entré Audio Standard de l'ordinateur hôte<br>
 * Elle envoie le Son capturé sur le canal UDP préalablement créé<br>
 * @author Romain Bustos
 * @author Matthieu Perrin
 * @version 1.0
 */
public class AudioCapture extends soundSetting{
    AbstractChatControleur controleur;  
    ClientUDP clientudp;
    protected boolean running;
    //ByteArrayOutputStream out;
    AudioFormat format;
    //float max;
    boolean activity;
    float seuil;
  
    /**
    *Constructeur
    */
    public AudioCapture(String IP, int port, AbstractChatControleur controleur, AudioFormat format) throws SocketException, UnknownHostException{        
        //if (Constant.debug)System.out.println("Audio Capture: " +controleur);
        this.format = getFormat();
        this.controleur = controleur;
        this.seuil = controleur.getLocalSoundSetting().getSeuil();
        clientudp = new ClientUDP(IP,port);     
        captureAudio();
    }
    
    /**
    *Lance la capture audio et appel le client UDP pour l'envoi
    */
    private void captureAudio() {
    try {
      DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
      final TargetDataLine line = (TargetDataLine)AudioSystem.getLine(info);
      line.open(format);
      line.start();
      Runnable runner = new Runnable() {
        int bufferSize = 640;
        byte buffer[] = new byte[bufferSize];

        @Override
        public void run() {
          //System.out.println("capture buferSize " +bufferSize);
          running = true;
          try {
            while (running) {
                int count = line.read(buffer, 0, buffer.length);   
                 if (count > 0) {
                     if(calculmoyenne(buffer) > seuil){
                         activity = true;
                         controleur.setActivityLine(activity);
                        // Envoie du buffer sur le socket UDP
                        clientudp.Push(buffer); 
                     }
                     activity = false;
                     controleur.setActivityLine(activity);
                  }
            }
            line.close();
          }catch (IOException e) {
            System.err.println("I/O problems: " + e);
            System.exit(-1);
          }
        }
      };
      Thread captureThread = new Thread(runner);
      captureThread.start();
    } catch (LineUnavailableException e) {
      System.err.println("Line unavailable: " + e);
      //System.exit(-2);
    }
  }
    /**
    *Calcule la moyenne d'un buffer de bytes passé en paramètre
    * @param buffer 
    * @return moyenne
    */
    private float calculmoyenne(byte buffer[]){
            float moyenne = 0;
            int max = 0;
            for(int i = 0; i < buffer.length;i++){
                max = max + Math.abs(buffer[i]);
                moyenne = (float) max / buffer.length;
                //System.out.println(moyenne);
            }
            return moyenne;
        }
 
    /**
    *arrête la Thread de capture Audio
    */
    public void Stop()
    {
        running = false;
    }
    
}
